﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using Dapper;

namespace GGGK.Film.Comm
{
    public class DapperHelper
    {
        public static readonly string connStr = ConfigurationHelper.GetConfiguration().GetSection("ConnectionStrings:DefaultConn").Value!;
        
        /// <summary>
        /// 查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="args"></param>
        /// <returns></returns>
         public static IEnumerable<T> Query<T>(string sql, object? args)
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                return conn.Query<T>(sql, args);
            }
        }

        /// <summary>
        /// 查询第一个数据，没有返回默认值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public static T? QueryFirstOrDefault<T>(string sql, object args)
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                return conn.QueryFirstOrDefault<T>(sql, args);
            }
        }

        /// <summary>
        /// 执行命令返回受影响的行数
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public static int Execute(string sql, object args)
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                return conn.Execute(sql, args);
            }
        }

        /// <summary>
        /// 执行命令返回第一行第一列数据
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public static object? ExecuteScalar(string sql, object args)
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                return conn.ExecuteScalar(sql, args);
            }
        }

        /// <summary>
        /// 执行命令返回第一行第一列数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public static T? ExecuteScalar<T>(string sql, object args)
        {
            using (SqlConnection connection = new SqlConnection(connStr))
            {
                return connection.ExecuteScalar<T>(sql, args);
            }
        }
    }
}
